package com.xczl.demo.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.xczl.demo.dao.UserDao;
import com.xczl.demo.dao.UserLevelDao;
import com.xczl.demo.domain.User;
import com.xczl.demo.domain.UserLevel;

@Service
public class UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserLevelDao userLevelDao;

	public void addUser(User user) {
		// 直接效验
		Assert.notNull(user, "用户实体不能为空");
		Assert.hasText(user.getUserName(), "账号不能为空");
		Assert.hasText(user.getPassword(), "密码不能为空");
		// 性别不能为空
		Assert.notNull(user.getSex(), "用户实体不能为空");
		// 数据库效验
		User temp = userDao.findByUserName(user.getUserName());
		Assert.isNull(temp, "当前账号已经被使用");
		// 初始化
		// 姓名为空设置为空字串符
		if (StringUtils.isBlank(user.getName())) {
			user.setName("");
		}
		if (user.getLevelId() == null) {
			user.setLevelId(1);
		}
		// 验证用户级别是否有效
		UserLevel level = userLevelDao.findById(user.getLevelId());
		Assert.notNull(level, "用户级别不存在,请联系管理员");
		// 用户等级不能为空
		userDao.insertUser(user);
	}
      
	public User findById(int id) {
		return userDao.findById(id);
	}

	public User login(String username, String password) {
		User user = userDao.findByUserName(username);
		if (user==null) {
			return null;
		}
		if (StringUtils.equals(password, user.getPassword())) {
			return user;
		}
		return null;
	}


}